/*
 * Copyright (C) 2017-2021
 * All rights reserved, Designed By 深圳中科鑫智科技有限公司
 * Copyright authorization contact 18814114118
 */
package com.shop.zkmall.oss.alioss.service.impl;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.BucketReferer;
import com.shop.zkmall.oss.alioss.AliOssProperties;
import com.shop.zkmall.oss.alioss.service.SafetyFileService;

import java.util.List;

public class SafetyFileServiceImpl implements SafetyFileService {

    private final OSSClient ossClient;

    private final AliOssProperties aliOssProperties;

    public SafetyFileServiceImpl(OSSClient ossClient, AliOssProperties aliOssProperties) {
        this.ossClient = ossClient;
        this.aliOssProperties = aliOssProperties;
    }

    @Override
    public void setSafety(List<String> refererList) {
        // 设置存储空间Referer列表。设为true表示Referer字段允许为空。
        BucketReferer br = new BucketReferer(true, refererList);
        ossClient.setBucketReferer(aliOssProperties.getBucketName(), br);
    }

    @Override
    public List<String> getSaftys() {
        // 获取存储空间Referer白名单列表。
        BucketReferer br = ossClient.getBucketReferer(aliOssProperties.getBucketName());
        List<String> refererList = br.getRefererList();
        return refererList;
    }

    @Override
    public void clearSafety() {
        // 防盗链不能直接清空，需要新建一个允许空Referer的规则来覆盖之前的规则。
        BucketReferer br = new BucketReferer();
        ossClient.setBucketReferer(aliOssProperties.getBucketName(), br);
    }
}
